package com.gylang.crypto.crypto;

import cn.hutool.crypto.CryptoException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 加解密上下文对象 存储所有得加解密方法策略
 *
 * @author gylang
 * data 2020/10/28
 * @version v0.0.1
 */
@Component
public class CryptoContext {

    private static final String MESSAGE = "加密异常, 不支持当前解析方式";
    @Autowired
    private Map<String, CryptoStrategy> cryptStrategy;

    public String decrypt(String strategy, String key, String content) {
        CryptoStrategy cryptoStrategy = cryptStrategy.get(strategy);
        if (null == cryptoStrategy) {
            throw new CryptoException(MESSAGE);
        }
        return cryptoStrategy.decrypt(key, content);
    }

    public String encrypt(String strategy, String key, String content) {
        CryptoStrategy cryptoStrategy = cryptStrategy.get(strategy);
        if (null == cryptoStrategy) {
            throw new CryptoException(MESSAGE);
        }
        return cryptoStrategy.encrypt(key, content);
    }

    public String sign(String strategy, String key, String content) {

        CryptoStrategy cryptoStrategy = cryptStrategy.get(strategy);
        if (null == cryptoStrategy) {
            throw new CryptoException(MESSAGE);
        }
        return cryptoStrategy.sign(key, content);
    }

    public boolean answer(String strategy, String key, String content) {
        CryptoStrategy cryptoStrategy = cryptStrategy.get(strategy);
        if (null == cryptoStrategy) {
            throw new CryptoException(MESSAGE);
        }
        return cryptoStrategy.answer(key, content);
    }


}
